﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TruckWatch.Cloud.Models;
using TruckWatch.Cloud.DAL;
using System.Data.SqlClient;
using System.Data;

namespace TruckWatch.Cloud.DAL
{
    public class TripPointDAL
    {
        public static List<TripPointNEF> GetAllTripPointsByDriverId(int driverId)
        {
            ParamBuilder pb = new ParamBuilder();
            pb.AddParam(System.Data.SqlDbType.VarChar, "@DriverId", driverId);

            string sql = @"
select 
    tp.Id,tp.TripId,tp.Latitude,tp.Longitude,tp.ArriveDate,tp.DriverId
from 
    TripPoint tp join Driver d on tp.DriverId = d.Id
where
	(d.Id = @DriverId)
    ";

            List<TripPointNEF> tripPoints = new List<TripPointNEF>();
            using (SqlDataReader reader = DataGeneral.ExecuteReader(sql, pb.Parameters, false))
            {
                while (reader.Read())
                {
                    TripPointNEF tripPoint = new TripPointNEF();
                    tripPoint.Id = (int)reader["Id"];
                    tripPoint.TripId = (int)reader["TripId"];
                    tripPoint.Latitude = (double)reader["Latitude"];
                    tripPoint.Longitude = (double)reader["Longitude"];
                    tripPoint.ArriveDate = ((DateTime)reader["ArriveDate"]).AddHours(-5);
                    tripPoint.DriverId = (int)reader["DriverId"];

                    tripPoints.Add(tripPoint);
                }
            }
            return tripPoints;
        }

        #region Update Location

        public static void UpdateLocation(TripPointNEF tripPoint)
        {
            ParamBuilder pb = new ParamBuilder();
            pb.AddParam(SqlDbType.Int, "@TripId", tripPoint.TripId);
            pb.AddParam(SqlDbType.Float, "@Latitude", tripPoint.Latitude);
            pb.AddParam(SqlDbType.Float, "@Longitude", tripPoint.Longitude);
            pb.AddParam(SqlDbType.DateTime, "@ArriveDate", tripPoint.ArriveDate.ToUniversalTime());
            pb.AddParam(SqlDbType.Int, "@DriverId", tripPoint.DriverId);

            string sql = @"insert into TripPoint (TripId,Latitude,Longitude,ArriveDate,DriverId) values (@TripId,@Latitude,@Longitude,@ArriveDate,@DriverId)";

            DataGeneral.ExecuteNonQuery(sql, pb.Parameters, false);
        }

        #endregion

    }
}
